/**
 * 
 */
package com.novartis.nims.trialsubmitter;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import com.novartis.nims.trialsubmitter.views.SwingView;

/**
 * @author Josh Snyder
 *
 */
public class ApplicationController {
	
	SwingView View;
	ApplicationConfiguration Configuration;
	
	ApplicationController(SwingView view, ApplicationConfiguration config) {
		this.View = view;
		this.Configuration = config;
	}

	public void execute() {
		try {
			validateDirectories();
		} catch (UserException e) {
			this.View.showErrorMessage(e.getMessage());
			return;
		}
		
		Logger logger = Logger.getRootLogger();
		logger.removeAllAppenders();
		try {
			logger.addAppender(new FileAppender(
					new PatternLayout("%d{HH:mm:ss} %-5p [%c{1}] %m%n"),
					this.View.getOutputDirectory() + File.separator + "nits.log"));
		} catch (IOException e) {
			this.View.showErrorMessage("Couldn't open file for logging. Try making sure the output directory is empty and writeable.");
			return;
		}
		logger.setLevel(Level.WARN);
		
		File inFile = new File(this.View.getInputDirectory());
		File outFile = new File(this.View.getOutputDirectory());
		
		TrialSubmitter trialSubmitter =	new TrialSubmitter(this.Configuration, inFile.toURI(), outFile.toURI());
		trialSubmitter.setSubmissionNumber(this.View.getSubmissionNumber());
		
		TrialSubmitterSwingWorker tssw = new TrialSubmitterSwingWorker(trialSubmitter);
		trialSubmitter.setController(tssw);
		
		trialSubmitter.setSort(this.View.getDoSort());
		trialSubmitter.setClean(this.View.getDoClean());					
		trialSubmitter.setMakeDescriptor(this.View.getDoODM());
		
		this.View.registerWorker(tssw);
		
		logger.info("Starting execution.");
		tssw.execute();
	}

	private void validateDirectories() throws UserException {
		String directoryString = this.View.getInputDirectory();
		
		File inputFile = new File(directoryString);
		if (! inputFile.exists()) {
			throw new UserException("Specified source directory does not exist. " +
				"Try using the Browse button to select a location.");
		}
		
		if (! inputFile.isDirectory()) {
			throw new UserException("Specified source directory is actually a file." +
				"Try using the Browse button to select a location.");
		}
		
		if (inputFile.list().length < 1) {
			throw new UserException("Specified source directory is empty." +
				"Try selecting a location that contains image files in one of its sub-directories.");
		}

		
		directoryString = this.View.getOutputDirectory();
		File outputFile = new File(directoryString);
		
		if (! outputFile.exists()) {
			throw new UserException("Specified submission directory does not exist. " +
				"Try using the Browse button to select a location.");
		}
		
		if (! outputFile.isDirectory()) {
			throw new UserException("Specified submission directory is actually a file. " +
				"Try using the Browse button to select a location.");
		}
		
		if ((outputFile.list().length > 1) ||
			(outputFile.list().length == 1 && !(outputFile.list()[0].equalsIgnoreCase("nits.log")))) {
			throw new UserException("Specified submission directory isn't empty. " +
				"Try selecting a location that doesn't contain any files or sub-directories.");
		}
		
		if (! outputFile.canWrite()) {
			throw new UserException("You can't write to specified submission directory. " +
				"Try changing the permissions on it, or selecting a new location.");
		}
	}

}
